package com.pengke.pangu.controller.sys;

import cn.dev33.satoken.stp.StpUtil;
import com.pengke.pangu.dto.MenuTree;
import com.pengke.pangu.common.utils.R;
import com.pengke.pangu.service.sys.entity.SysPermission;
import com.pengke.pangu.service.sys.service.ISysPermissionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class SysController {

    @Resource
    private ISysPermissionService sysPermissionService;

    @GetMapping("/getMenu")
    public R getMenu() {
        Integer userId = Integer.parseInt(StpUtil.getLoginId().toString());
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("id",userId);
        param.put("type","B");
        param.put("hidden","0");
        List<SysPermission> sysPermissionList = sysPermissionService.getSysPermissionByUserId(param);
        List<MenuTree> menuTreeList = sysPermissionList.stream().map(m -> {
            MenuTree menuTree = new MenuTree();
            menuTree.setId(m.getId());
            menuTree.setPid(m.getPid());
            menuTree.setTitle(m.getTitle());
            menuTree.setPath(m.getPath());
            menuTree.setIcon(m.getIcon());
            menuTree.setSelf(m);
            return menuTree;
        }).toList();

        List<MenuTree> menuTrees = menuTreeList.stream().filter(l -> l.getPid().equals(0)).peek(m -> m.setChildren(getChildren(m, menuTreeList))).collect(Collectors.toList());

        return R.ok(menuTrees);
    }

    private List<MenuTree> getChildren(MenuTree root, List<MenuTree> all) {
        return all.stream().filter(m -> Objects.equals(m.getPid(), root.getId())).peek(m -> m.setChildren(getChildren(m, all))).collect(Collectors.toList());
    }

    @GetMapping("/getRoute")
    public R getRoute(){
        Integer userId = Integer.parseInt(StpUtil.getLoginId().toString());
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("id",userId);
        param.put("type","B");
        List<SysPermission> sysPermissionList = sysPermissionService.getSysPermissionByUserId(param);
        return R.ok(sysPermissionList);
    }

}
